package com.hdsx.webservice.gateway.filter;

import com.hdsx.webservice.gateway.config.SwaggerProvider;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import java.net.URI;
import java.util.LinkedHashSet;
import java.util.Map;

@Component
public class SwaggerHeaderFilter extends AbstractGatewayFilterFactory {

    private static final String HEADER_NAME = "X-Forwarded-Prefix";

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getURI().getPath();
            if (!StringUtils.endsWithIgnoreCase(path, SwaggerProvider.API_URI)) {
                return chain.filter(exchange);
            }

            Map<String, Object>  basePath = exchange.getAttributes();
            LinkedHashSet<URI> path1 = (LinkedHashSet<URI>) basePath.get("org.springframework.cloud.gateway.support.ServerWebExchangeUtils.gatewayOriginalRequestUrl");
            String base = "";
            for (URI uri : path1) {
                base = uri.getPath();
                base = base.substring(0, base.lastIndexOf(SwaggerProvider.API_URI));
            }
            ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, base).build();
            ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
            return chain.filter(newExchange);
        };
    }

}